package showtime.framework.engine.map.parser
{
	import showtime.framework.engine.map.rpg.Group;
	import showtime.framework.engine.map.rpg.MapLayer;
	import showtime.framework.engine.map.rpg.ObjectHolder;
	

	public class TiledParser extends BaseMapParser
	{					
		public var orientation:String = null;
		
		public var layers:Array = null;
		
		public var groups:Array = null;
		
		public function TiledParser()
		{
			super();
		}
		
		override public function destroy():void
		{
			super.destroy();
			
			layers = null;
			groups = null;
		}
		
		override public function parse():void
		{
			super.parse();
			
			version = source.@version;

			orientation = source.@orientation;

			layers = [];
			
			var layer:MapLayer = null;
			for each (var layerXML:XML in source.elements("layer"))
			{				
				layer = new MapLayer(layerXML.@name, layerXML.@width, layerXML.@height, source.@tilewidth, source.@tileheight, source.tileset.image.@width / source.tileset.@tilewidth, source.tileset.image.@height / source.tileset.@tileheight);

				for each (var tileXML:XML in layerXML.data.elements("tile"))
				{					
					layer.data.push(tileXML.@gid);
				}
				
				layers.push(layer);
			}
			
			// Analyze object group.
			groups = [];			
			var group:Group = null;
			for each (var groupXML:XML in source.elements("objectgroup"))
			{
				group = new Group();
				group.name = groupXML.@name;
				group.width = groupXML.@width;
				group.height = groupXML.@height;
				group.objects = [];
				
				var object:ObjectHolder = null;
				for each (var objectXML:XML in groupXML.elements("object"))
				{
					object = new ObjectHolder();
					object.name = objectXML.@name;
					object.type = objectXML.@type;
					object.width = objectXML.@width;
					object.height = objectXML.@height;
					object.x = objectXML.@x;
					object.y = objectXML.@y - source.@tileheight;
			
					object.properties = [];
					for each (var propertyXML:XML in objectXML.properties.elements("property"))
					{
						object.properties[propertyXML.@name] = propertyXML.@value;
					}
					
					group.objects.push(object);
				}
				groups.push(group);
			}
		}
		
	}
}